<template>
  <div
    :class="{
      'code-page': isEmailSent,
      'code-complete': isEmailSent && isCodeComplete,
    }"
    class="container"
  >
    <transition name="fade">
      <button v-if="isEmailSent" class="back-btn" type="button" @click="goBack">
        <i class="bx bx-arrow-back"></i>
        返回修改邮箱
      </button>
    </transition>

    <div class="form-box">
      <form @submit.prevent="handleSubmit">
        <h1>找回密码</h1>
        <p class="description">
          {{
            isEmailSent
              ? "请输入您收到的验证码"
              : "请输入您的邮箱地址，我们将向您发送验证码"
          }}
        </p>

        <transition mode="out-in" name="fade-slide">
          <div v-if="!isEmailSent" key="email" class="input-box">
            <input
              v-model="email"
              placeholder="邮箱地址"
              required
              type="email"
            />
            <i class="bx bxs-envelope"></i>
          </div>

          <div v-else key="verification" class="verification-box">
            <div class="email-display">{{ email }}</div>
            <div class="code-inputs">
              <input
                v-for="(_digit, index) in 6"
                :key="index"
                :ref="(el:any) => (codeInputs[index] = el)"
                v-model="verificationDigits[index]"
                maxlength="1"
                type="text"
                @input="handleCodeInput(index)"
                @keydown="handleKeydown($event, index)"
                @paste="handlePaste"
              />
            </div>
            <div v-if="countdown > 0" class="resend-code">
              {{ countdown }}秒后可重新发送
            </div>
            <div v-else class="resend-code clickable" @click="resendCode">
              重新发送验证码
            </div>
          </div>
        </transition>

        <transition name="fade">
          <button
            v-if="!isEmailSent || isCodeComplete"
            :disabled="loading"
            class="btn"
            type="submit"
          >
            {{ isEmailSent ? "验证并重置密码" : "发送验证码" }}
          </button>
        </transition>

        <div class="back-to-login">
          <a href="/user/login"><i class="bx bx-arrow-back"></i> 返回登录</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onBeforeUnmount, ref } from "vue";

const email = ref("");
const verificationDigits = ref(Array(6).fill(""));
const codeInputs = ref<HTMLInputElement[]>([]);
const isEmailSent = ref(false);
const loading = ref(false);
const countdown = ref(0);
let countdownTimer: ReturnType<typeof setInterval> | null = null;

const isCodeComplete = computed(() => {
  return verificationDigits.value.every((digit) => digit !== "");
});

const handleCodeInput = (index: number) => {
  const value = verificationDigits.value[index];

  // 确保输入为单个数字
  if (!/^\d*$/.test(value)) {
    verificationDigits.value[index] = "";
    return;
  }

  // 自动跳转到下一个输入框
  if (value && index < 5) {
    codeInputs.value[index + 1]?.focus();
  }
};

const handleKeydown = (event: KeyboardEvent, index: number) => {
  if (
    event.key === "Backspace" &&
    !verificationDigits.value[index] &&
    index > 0
  ) {
    // 当前框为空且按下删除键时，跳转到前一个输入框
    verificationDigits.value[index - 1] = "";
    codeInputs.value[index - 1]?.focus();
  }
};

const handlePaste = (event: ClipboardEvent) => {
  event.preventDefault();
  const pastedData = event.clipboardData?.getData("text");
  if (!pastedData) return;

  // 只取数字
  const digits = pastedData.replace(/\D/g, "").slice(0, 6);
  digits.split("").forEach((digit, index) => {
    if (index < 6) {
      verificationDigits.value[index] = digit;
    }
  });
};

const resendCode = async () => {
  if (countdown.value > 0) return;
  await sendVerificationCode();
  startCountdown();
};

// 发送验证码
const sendVerificationCode = async () => {
  try {
    await new Promise((resolve) => setTimeout(resolve, 1000));
    return true;
  } catch (error) {
    console.error("发送验证码失败:", error);
    return false;
  }
};

// 验证验证码
const verifyCode = async () => {
  try {
    await new Promise((resolve) => setTimeout(resolve, 1000));
    return true;
  } catch (error) {
    console.error("验证码验证失败:", error);
    return false;
  }
};

// 开始倒计时
const startCountdown = () => {
  // 先清除可能存在的旧计时器
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }

  countdown.value = 60;
  countdownTimer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      if (countdownTimer) {
        clearInterval(countdownTimer);
        countdownTimer = null;
      }
    }
  }, 1000);
};

// 表单提交处理
const handleSubmit = async () => {
  if (loading.value) return;

  loading.value = true;
  try {
    if (!isEmailSent.value) {
      const success = await sendVerificationCode();
      if (success) {
        isEmailSent.value = true;
        startCountdown();
        // 添加延时以确保DOM更新完成后再聚焦
        setTimeout(() => {
          codeInputs.value[0]?.focus();
        }, 500);
      }
    } else {
      const success = await verifyCode();
      if (success) {
        console.log("验证成功");
      }
    }
  } catch (error) {
    console.error("操作失败:", error);
  } finally {
    loading.value = false;
  }
};

// 组件销毁前清理定时器
onBeforeUnmount(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
});

// 添加返回上一步功能
const goBack = () => {
  isEmailSent.value = false;
  // 确保清除计时器
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
  countdown.value = 0;
  // 清空验证码输入
  verificationDigits.value = Array(6).fill("");
};
</script>

<style scoped>
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800;900&display=swap");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(90deg, #e2e2e2, #c9d6ff);
}

.container {
  position: relative;
  width: 360px;
  background: #fff;
  border-radius: 30px;
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.2);
  padding: 30px;
  overflow: hidden;
  min-height: 320px;
  transition: all 0.3s ease;
}

.container.code-page {
  min-height: 380px;
  padding-top: 40px;
}

.container.code-page.code-complete {
  min-height: 440px;
}

.container h1 {
  font-size: 32px;
  text-align: center;
  margin-bottom: 15px;
  color: #333;
}

.description {
  text-align: center;
  color: #666;
  font-size: 14px;
  margin-bottom: 20px;
}

.input-box {
  position: relative;
  margin: 20px 0;
  height: 50px;
}

.input-box input {
  width: 100%;
  padding: 13px 50px 13px 20px;
  background: #f5f5f5;
  border-radius: 8px;
  border: 2px solid transparent;
  outline: none;
  font-size: 16px;
  color: #333;
  font-weight: 500;
  transition: all 0.3s ease;
}

.input-box input::placeholder {
  color: #888;
  font-weight: 400;
}

.input-box i {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 20px;
  color: #888;
}

.input-box input:focus {
  border-color: #7494ec;
  background: #fff;
}

.btn {
  width: 100%;
  height: 48px;
  background: #7494ec;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border: none;
  cursor: pointer;
  font-size: 16px;
  color: #fff;
  font-weight: 600;
  margin-bottom: 20px;
  transition: all 0.3s ease;
  opacity: 1;
}

.btn:hover {
  background: #6384db;
}

.btn:disabled {
  background: #a5b7e7;
  cursor: not-allowed;
}

.btn span {
  margin-left: 5px;
  font-size: 14px;
}

.back-to-login {
  text-align: center;
}

.back-to-login a {
  color: #333;
  text-decoration: none;
  font-size: 14.5px;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.back-to-login a:hover {
  color: #7494ec;
}

/* 动画相关样式 */
.fade-slide-enter-active,
.fade-slide-leave-active {
  transition: all 0.3s ease;
  position: absolute;
  width: 100%;
}

/* 默认动画：验证码页面从右边进入，邮箱页面从左边退出 */
.fade-slide-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.fade-slide-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

/* 返回时的动画：邮箱页面从左边进入，验证码页面从右边退出 */
.container:not(.code-page) .fade-slide-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.container:not(.code-page) .fade-slide-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

/* 确保动画元素不会影响布局 */
.verification-box,
.input-box {
  position: relative;
  width: 100%;
}

.verification-box {
  margin: 25px 0;
}

.code-inputs {
  display: flex;
  gap: 8px;
  justify-content: center;
  margin-bottom: 15px;
}

.code-inputs input {
  width: 45px;
  height: 45px;
  border: 2px solid #ddd;
  border-radius: 8px;
  text-align: center;
  font-size: 20px;
  font-weight: 600;
  color: #333;
  background: #f5f5f5;
  transition: all 0.3s ease;
  outline: none;
}

.code-inputs input:focus {
  border-color: #7494ec;
  background: #fff;
  box-shadow: 0 0 5px rgba(116, 148, 236, 0.3);
}

.resend-code {
  text-align: center;
  color: #666;
  font-size: 14px;
  margin-top: 15px;
}

.resend-code.clickable {
  color: #7494ec;
  cursor: pointer;
  transition: color 0.3s ease;
}

.resend-code.clickable:hover {
  color: #6384db;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 确保输入框只能输入数字 */
.code-inputs input::-webkit-outer-spin-button,
.code-inputs input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.code-inputs input[type="number"] {
  -moz-appearance: textfield;
}

/* 移动端适配 */
@media screen and (max-width: 450px) {
  .code-inputs {
    gap: 6px;
  }

  .code-inputs input {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }
}

/* 更新返回按钮样式 */
.back-btn {
  position: absolute;
  top: 20px;
  left: 20px;
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  padding: 8px;
  transition: all 0.3s ease;
  z-index: 10;
}

.back-btn:hover {
  color: #7494ec;
  transform: translateX(-3px);
}

.back-btn i {
  font-size: 18px;
}

/* 移动端适配更新 */
@media screen and (max-width: 450px) {
  .container {
    width: 90%;
    min-height: 300px;
    padding: 25px 20px;
  }

  .container.code-page {
    min-height: 400px;
    padding-top: 35px;
  }

  .container.code-page.code-complete {
    min-height: 460px;
  }
}

.email-display {
  text-align: center;
  color: #666;
  font-size: 14px;
  margin-bottom: 15px;
  background: #f5f5f5;
  padding: 8px 15px;
  border-radius: 6px;
  word-break: break-all;
}

.form-box {
  position: relative;
  padding-top: 20px;
}

/* 动画优化 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 移除focus-visible的默认样式 */
.code-inputs input:focus-visible {
  outline: none;
  border-color: #7494ec;
  background: #fff;
  box-shadow: 0 0 5px rgba(116, 148, 236, 0.3);
}
</style>
